package model

import (
	"DomCtrlCenter/data"
	"encoding/json"
	"fmt"
	"strconv"
)

type TimerSetData struct {
	IsTimerOn int      `json:"timer-on"`
	Ons       []string `json:"ons"`
	Offs      []string `json:"offs"`
}

var AirConfig data.Config
var TimerData TimerSetData
var TimerForceDone []chan struct{}

/**
 * [ SetTemperature,SetFan,SetPower,TimerOn,TimerJson ]
 */

func AirConfigInit() {
	var err error
	AirConfig, err = data.GenerateConfig("aircon.txt")
	if err != nil {
		fmt.Println("创建配置文件时发生错误")
	}
	if t, ok := AirConfig.KeyValueMap["SetTemperature"]; ok {
		SetTemperature, _ = strconv.Atoi(t)
	} else {
		AirConfig.AddKVLine("SetTemperature", strconv.Itoa(SetTemperature))
	}
	if t, ok := AirConfig.KeyValueMap["SetFan"]; ok {
		SetFanSpeed, _ = strconv.Atoi(t)
	} else {
		AirConfig.AddKVLine("SetFan", strconv.Itoa(SetFanSpeed))
	}
	if t, ok := AirConfig.KeyValueMap["SetPower"]; ok {
		SetAirPower = t == "1"
	} else {
		if SetAirPower {
			t = "1"
		} else {
			t = "0"
		}
		AirConfig.AddKVLine("SetPower", t)
	}
	if t, ok := AirConfig.KeyValueMap["TimerOn"]; ok {
		TimerOn = t == "1"
	} else {
		if TimerOn {
			t = "1"
		} else {
			t = "0"
		}
		AirConfig.AddKVLine("TimerOn", t)
	}
	if t, ok := AirConfig.KeyValueMap["TimerJson"]; ok {
		err := json.Unmarshal([]byte(t), &TimerData)
		if err != nil {
			fmt.Println("解析定时器时出现错误")
		}
		StartAllTimer()
	} else {
		TimerData.Ons = make([]string, 0)
		TimerData.Offs = make([]string, 0)
		tt, err := json.Marshal(TimerData)
		if err != nil {
			fmt.Println("解析定时器时出现错误2")
		}
		AirConfig.AddKVLine("TimerJson", string(tt))
	}
	AirConfig.SerializeToFile()
}
